package cn.geminis.crypto.csp.parameter;

import org.bouncycastle.asn1.*;
import org.bouncycastle.crypto.CipherParameters;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @author Allen
 */
public class InitMacCipherParameters implements CipherParameters {

    private boolean encrypted;
    private byte[] key;

    public InitMacCipherParameters(boolean encrypted, byte[] key) {
        this.encrypted = encrypted;
        this.key = key;
    }

    public InitMacCipherParameters(byte[] data) {
        try {
            ASN1Sequence sequence = (ASN1Sequence) DERSequence.fromByteArray(data);
            this.encrypted = ASN1Boolean.getInstance(sequence.getObjectAt(0)).isTrue();
            this.key = DEROctetString.getInstance(sequence.getObjectAt(1)).getOctets();
        } catch (IOException e) {
            throw new RuntimeException("解析Mac初始化参数错误", e);
        }
    }

    public boolean isEncrypted() {
        return encrypted;
    }

    public byte[] getKey() {
        return key;
    }

    public byte[] encode() {
        try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
            DERSequenceGenerator generator = new DERSequenceGenerator(stream);
            generator.addObject(ASN1Boolean.getInstance(this.encrypted));
            generator.addObject(new DEROctetString(this.key));
            generator.close();
            return stream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("Mac初始化参数编码错误", e);
        }
    }
}
